var express = require('express');
var router = express.Router();
let db = require('../tools/DB');
let to = require('../tools/to');
let uuid = require('uuid');
let jwt = require('jsonwebtoken');
let {
    SECRET
} = require('../tools/config');
let formidable = require('formidable');
let path =require('path');
let fs = require('fs');

//获取用户信息路由

router.get('/:mid', async (req,res)=>{
  let {mid} = req.params;
  let sql = `select id,mid,realname,tel,sex,birthdate,city,head_photo_url,username from e_member where mid=?`;
  let [err,result] = await to(db.query(sql,[mid]))
  if(!err){
    res.json({code:200,msg:'成功',data:result});
  }else{
    res.json({code:500,msg:'获取用户失败',data:err});
    
  }
})

//更新用户信息
router.put('/',async (req,res)=>{
  let {mid,realname,username,sex,birthdate} = req.body;

  let sql = 'update e_member set realname=?,username=?,sex=?,birthdate=? where mid=?';
  let [err,result] = await to(db.query(sql,[realname,username,sex,birthdate,mid]));
  if(!err){
    if(result.affectedRows>0){
      res.json({code:200,msg:'成功',data:null})
    }else{
      res.json({code:208,msg:'提交失败',data:null})
    }
  }else{
    res.json({code:400,msg:'失败',data:err})
    
  }
})


//更新用户头像
router.post('/upload', (req,res)=>{
  
  const form =formidable({multiples:true,uploadDir:'./uploads/avatar'});
  form.parse(req,async (err,fields,files)=>{
    console.log(files);
    let {mid} = fields;
    let originName = files.file1.name;
    let extName  = path.extname(originName);
    let oldFile = files.file1.path;
    //更名
    let newFile = oldFile+extName;
    fs.renameSync(oldFile,newFile);
    
    let sql = 'update e_member set head_photo_url=? where mid=?';
    let [error,result] = await to (db.query(sql,[newFile,mid]));
    if(!error){
      if(result.affectedRows>0){
        res.json({code:200,data:{newFile},msg:'用户头像上传成功'});
      }else{
        res.json({code:200,data:null,msg:'用户头像上传失败，请检查参数'});

      }
      
    }else{
      res.json({code:500,data:err,msg:'更新失败'})
    }
  })
})

//获取会员报名的课程
router.post('/mycourse',async (req,res)=>{
  let {mid} = req.body;
  console.log(mid);
  let sql =`select e_course.subject_name,e_course.image_src,e_course.type_name,e_course.area_name,e_course.cid  from e_course INNER JOIN e_order on e_order.cid = e_course.cid where e_order.mid = ?`
  let [err,result] = await to(db.query(sql,[mid]));
  if(!err){
    res.json({code:200,data:result,msg:'成功'});
  }else{
    res.json({code:500,data:err,msg:'失败'});
  }
})



module.exports = router;
